from app import app
import math


'''
自定义分页
'''
def Pagination(page_num,totals):
    ret = {"prev_page": page_num - 1,
           "next_page": page_num + 1,
           "current_page": 0,
           "total_pages": 0,
           "max_page": 0,
           "page_size": app.config["PAGE_SIZE"],
           "totals": totals,
           "offset": 0,
           "page_range": None
           }

    ret["total_pages"] = math.ceil(totals / ret["page_size"])
    ret["max_page"] = ret["total_pages"]


    if page_num <= 1:
        page_num = 1
        ret["prev_page"] = 1
    if page_num >= ret["max_page"]:
        page_num = ret["max_page"]
        ret["next_page"] = ret["max_page"]

    ret["current_page"] = page_num

    if totals == 0:
        ret["offset"] = 0
    else:
        ret["offset"] = (ret["current_page"] - 1) * ret["page_size"]

    page_range = []
    for i in range(1,ret["max_page"]+1):
        page_range.append(i)
    ret["page_range"] = page_range

    return ret


"""
用户服务类
"""
import hashlib,random
from datetime import datetime

class UserService():

    @staticmethod
    def geneAuthCode(user):
        md5 = hashlib.md5()
        s = str(user.uid) + user.login_name + user.login_pwd + user.login_salt
        md5.update(s.encode('utf-8'))
        return md5.hexdigest()


    @staticmethod
    def genePwd(pwd,salt):
        md5 = hashlib.md5()
        s = pwd + str(salt)
        md5.update(s.encode('utf-8'))
        return md5.hexdigest()

    @staticmethod
    def geneSalt():
        return str(random.randint(100000,999999))

    @staticmethod
    def geneTime():
        return datetime.now().strftime("%Y-%m-%d %H:%M:%S")


"""
日志服务类
"""
from flask import request,g
import json
from app import db
from models.log.NormalLog import NormalLog
from models.log.ErrorLog import ErrorLog

class LogService():
    @staticmethod
    def addNormalLog():
        try:
            log = NormalLog()
            log.target_url = request.url
            log.referer_url = request.referrer
            log.ip = request.remote_addr
            log.query_params = json.dumps(request.values.to_dict())

            if "current_user" in g and g.current_user is not None:
                log.uid = g.current_user.uid

            log.ua = request.headers.get("User-Agent")
            log.created_time = UserService.geneTime()

            db.session.add(log)
            db.session.commit()

        except:
            return True



    @staticmethod
    def addErrorLog(content):
        try:
            log = ErrorLog()
            log.target_url = request.url
            log.referer_url = request.referrer
            log.query_params = json.dumps(request.values.to_dict())
            log.content = content
            log.created_time = UserService.geneTime()

            db.session.add(log)
            db.session.commit()
        except:
            return True


# 生成订单id号
def geneOrderId(id):
    return datetime.now().strftime("%Y%m%d%H%M%S")